using System.Collections.Generic;
using System.Linq;
using BizTalk.BuildGenerator.MetaData;

namespace BizTalk.BuildGenerator
{
    /// <summary>
    /// Used to sort the application resources to have the correct build order
    /// </summary>
    public class ApplicationResourceSorter
    {
        /// <summary>
        /// Sorts the resources
        /// </summary>
        /// <param name="resources"></param>
        public static void Sort(List<ApplicationResource> resources)                       
        {
            var tempResources = new Queue<ApplicationResource>();

            foreach (var resource in resources.Where(resource => resource.DependantResources.Count == 0))
            {
                tempResources.Enqueue(resource);
            }

            foreach (var resource in resources)
            {
                AddResource(resource, tempResources);
            }

            resources.Clear();
            resources.AddRange(tempResources.ToArray());
        }

        /// <summary>
        /// Adds resources 
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="tempResources"></param>
        private static void AddResource(ApplicationResource resource, Queue<ApplicationResource> tempResources)
        {
            if (tempResources.Contains(resource))
                return;

            foreach (var dependancy in resource.DependantResources)
            {
                AddResource(dependancy, tempResources);
            }

            tempResources.Enqueue(resource);
        }
    }
}
